package com.liehu.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liehu.user.pojo.Employee;
import com.liehu.user.pojo.Employee;
import com.liehu.user.pojo.EncryptedData;
import com.liehu.user.pojo.Role;
import com.liehu.user.service.EmployeeService;
import com.liehu.user.service.EmployeeService;
import com.liehu.user.service.RoleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import util.HttpClientUtil;
import util.JwtUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/employee")
@CrossOrigin //跨域处理
@Api(value = "/employee",description = "职工")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleService roleService; //角色service
    @Autowired
    private RedisTemplate redisTemplate; //redis
    @Autowired
    private JwtUtil jwtUtil; // JWt令牌工具类
    @Autowired
    private HttpClientUtil httpClientUtil;//http工具类



    /**
     * 根据角色Id查询业务员
     */
    @ApiOperation(value = "根据角色Id查询业务员", notes = "根据角色Id查询业务员")//描述
    @GetMapping("/role/{roleId}")
    public Result findByRoleId(@PathVariable("roleId") String roleId){
        return  new Result(true, StatusCode.OK,"查询成功！",employeeService.findByRoleId(roleId));
    }


    /**
     * 查询所有
     */
    @ApiOperation(value = "查询全部回复", notes = "查询全部回复")//描述
    @GetMapping()
    public Result findAll(){
        return  new Result(true, StatusCode.OK,"查询成功！",employeeService.findAll());
    }

    /**
     * 根据id查询
     */
    @ApiOperation(value = "根据id查询", notes = "根据id查询")//描述
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id){
        return  new Result(true, StatusCode.OK,"查询成功！",employeeService.findById(id));
    }
    /**
     * 插入一条数据
     */
    @ApiOperation(value = "插入一条数据", notes = "插入一条数据-限管理员操作,新增员工默认密码为123456")//描述
    @PostMapping()
    public Result save(@RequestBody Employee employee){
        employeeService.save(employee);
        return  new Result(true, StatusCode.OK,"新增成功！");
    }

    /**
     * 根据id修改记录
     * @param Employee
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id修改记录", notes = "根据id修改记录--限管理员操作")//描述
    @PutMapping("/{id}")
    public Result update(@RequestBody Employee Employee,@PathVariable("id") String id){
        Employee.setId(id);//给reply植入id
        employeeService.update(Employee);
        return  new Result(true, StatusCode.OK,"修改成功！");
    }

    /**
     * 根据id删除
     */
    @ApiOperation(value = "根据id删除", notes = "根据id删除-限管理员操作")//描述
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") String id){
        employeeService.deleteById(id);
        return  new Result(true, StatusCode.OK,"删除成功！");
    }

    /**
     * 分页查询
     */
    @ApiOperation(value = "分页查询", notes = "不带条件的分页查询")//描述
    @GetMapping("/{page}/{size}")
    public Result findByPage(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
        Page<Employee> list = employeeService.findByPage(page, size);
        return  new Result(true, StatusCode.OK,"查询成功！",new PageResult<Employee>(list.getTotal(),list.getRecords()));
    }

    /**
     * 带条件的分页查询
     */
    @ApiOperation(value = "分页查询", notes = "带条件的分页查询")//描述
    @PostMapping("/search/{page}/{size}")
    public Result findByPageSearch(@RequestBody Employee Employee,@PathVariable("page") Integer page,@PathVariable("size") Integer size){
        Page<Employee> list = employeeService.findByPage(Employee, page, size);
        return  new Result(true, StatusCode.OK,"查询成功！",new PageResult<Employee>(list.getTotal(),list.getRecords()));
    }

    /**
     * 发送短信
     */
    @ApiOperation(value = "发送短信", notes = "发送短信")//描述
    @PostMapping("/send/{mobile}")
    public Result sendMsm(@PathVariable("mobile") String mobile){
        //屏蔽，防止短信乱发
        Integer sendCheckCode = (Integer) redisTemplate.opsForValue().get("sendCheckCode"+mobile);

        if(sendCheckCode!=null  && sendCheckCode%2 == 0){
            return new Result(false,StatusCode.REPERROR,"短信发送次数过多，请稍后再试！");
        }
        else if(sendCheckCode!=null && sendCheckCode%2 != 0){
            //发送短信
            employeeService.sendMsm(mobile);
            //状态码自增后保存到缓存,有效时间为1分钟
            sendCheckCode++;
            redisTemplate.opsForValue().set("sendCheckCode"+mobile,sendCheckCode,1L,TimeUnit.MINUTES);
            return new Result(true,StatusCode.OK,"发送成功！");
        }
        else if(sendCheckCode ==null){
            //如果为null，说明已经过期或第一次发送
            employeeService.sendMsm(mobile);
            return new Result(true,StatusCode.OK,"发送成功！");
        }else{
            return new Result(false,StatusCode.ERROR,"数据异常！");
        }


    }


    /**
     * 用户登录
     */
    @ApiOperation(value = "根据工号+密码登录", notes = "根据工号+密码登录")//描述
    @PostMapping("/login/password")
    public Result loginByPassword(@RequestBody Employee Employee){
        //1.根据电话号码和密码进行查询 --先鉴权
        Employee  = employeeService.loginByPassword(Employee.getJobNumber(),Employee.getPassword());
        //2.如果查询的对象为空，则提示账户密码错
        if(Employee == null){
            return new Result(false,StatusCode.LOGINERROR,"用户名或密码错误");
        }
        //3.如果不为空，先根据该用户的角色id去查询角色信息
        String roleId = Employee.getRoleId();
        //根据roleId去查询该角色信息
        Role role = roleService.findById(roleId);
        String token = jwtUtil.createJWT(Employee.getId(), Employee.getLoginName(), role.getRoleName());

        //4.一切顺利，颁发Token  -- 授权
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("roles",role.getRoleName());
        return new Result(true,StatusCode.OK,"登录成功！",map);
    }


    /**
     * 获取当前登录的用户信息
     * @return
     */
    @ApiOperation(value = "获取当前登录的用户信息", notes = "前端通过传入当前登录的token来获取当前登录的用户信息") //描述
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        Employee userInfo = employeeService.getUserInfo();
        if(userInfo == null){
            return new Result(false,StatusCode.ERROR,"token有误！");
        }
        return new Result(true,StatusCode.OK,"获取成功！",userInfo);
    }

    /**
     * 修改当前登录职工密码
     */
    @ApiOperation(value = "修改当前登录职工密码", notes = "修改当前登录职工密码，仅限员工调用，如管理员修改自身或其他职工密码，请勿调用此接口")//描述
    @PutMapping("/login/password")
    public Result updateByPassword(@RequestBody Employee employee){
        employeeService.updateByPassword(employee.getPassword());
        return new Result(true,StatusCode.OK,"修改成功！");
    }

    /**
     * 修改员工的状态为离职
     */
    @ApiOperation(value = "修改员工的状态为离职", notes = "仅用于将员工状态由在职转为离职，且需要管理员权限操作")//描述
    @PutMapping("/updateStatus/{employeeId}")
    public Result updateStatus(@PathVariable("employeeId") String employeeId){
        employeeService.updateStatus(employeeId);
        return  new Result(true, StatusCode.OK,"修改成功！");
    }
    /**
     * 刷新(更新)业务员队列
     */

    @ApiOperation(value = "刷新(更新)业务员队列", notes = "刷新(更新)业务员队列，且需要管理员权限操作")//描述
    @PutMapping("/update/EmployeeList/{roleId}")
    public Result updateEmployeeList(@PathVariable("roleId") String roleId){
        employeeService.updateEmployeeList(roleId);
        return  new Result(true, StatusCode.OK,"操作成功！");
    }





}
